package com.hwatsang.dao;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.hwatsang.model.SmsAuthCode;

public class HibernateSmsAuthCodeDaoImpl extends HibernateDaoSupport implements SmsAuthCodeDao {
	
	private static final Logger logger = LoggerFactory.getLogger(HibernateSmsAuthCodeDaoImpl.class);
	
	private static final String ENTITY_NAME = "SmsAuthCode";
	
	public String createSmsAuthCode(SmsAuthCode smsAuthCode) {
		
		logger.debug("Creating smsAuthCode [userId={}, authCode={}].", smsAuthCode.getUserId(), smsAuthCode.getAuthCode()) ;
		
		return String.valueOf(getHibernateTemplate().save(smsAuthCode));		
	}

	@SuppressWarnings("unchecked")
	public SmsAuthCode getAuthCodeByUserId(long userId) {
		logger.debug("Getting smsAuthCode for user {}.", userId);
		
//		List<SmsAuthCode> codes = getSession().createCriteria(ENTITY_NAME).add(Restrictions.eq("userId", userId)).list();
		List<SmsAuthCode> codes = getHibernateTemplate().find("from SmsAuthCode where userId = " + userId);
		
		if(codes.size() > 0) {
			return codes.get(0);
		} else {
			return null;
		}
	}

	public boolean updateSmsAuthCode(SmsAuthCode smsAuthCode) {
		logger.debug("Updating sms auth code for user {}.", smsAuthCode.getUserId());
		
		getHibernateTemplate().update(smsAuthCode);
		return true;
	}

	public boolean deleteSmsAuthCodeById(long id) {
		logger.debug("Deleting sms auth code {}.", id);
		
		SmsAuthCode code = (SmsAuthCode)getHibernateTemplate().get(ENTITY_NAME, id);
		if(code != null) {
			getHibernateTemplate().delete(code);
			return true;
		} else {
			return false;
		}
	}

	public boolean deleteSmsAuthCodeByUserId(long userId) {
		logger.debug("Deleting sms auth code for user {}.", userId);
		
		SmsAuthCode code = getAuthCodeByUserId(userId);
		if(code != null) {
			getHibernateTemplate().delete(code);
			return true;
		} else {
			return false;
		}
	}

}
